<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="100px">
      <el-form-item label="申请单号" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入申请单号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="人员姓名" prop="personName">
        <el-input v-model="queryParams.personName" placeholder="请输入人员姓名"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发票编号" prop="invoiceCode">
        <el-input v-model="queryParams.invoiceCode" placeholder="请输入发票编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="审核状态" prop="payStatus">
        <el-select clearable placeholder="请选择审核状态" v-model="queryParams.assessStatus">
          <el-option :key="dict.value"
                     :label="dict.label" :value="dict.value" v-for="dict in dict.type.apply_assess_status"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上传发票" prop="isInvoice">
        <el-radio-group v-model="queryParams.isInvoice" @change="getList">>
          <el-radio v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="回款状态" prop="payStatus">
        <el-select clearable placeholder="请选择回款状态" v-model="queryParams.payStatus">
          <el-option :key="dict.value"
                     :label="dict.label" :value="dict.value" v-for="dict in dict.type.apply_pay_status"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" >导出</el-button>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading"  :data="dataList" @selection-change="handleSelectionChange" ref="table"
              show-summary :summary-method="getSummaries" :max-height="tableMaxHeight"  @sort-change="handleSortChange">
      <el-table-column type="selection" width="60" align="center"/>
      <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
      <el-table-column sortable label="申请单号 " align="center" prop="nos" width="120"/>
      <el-table-column  label="供应商名称" align="center" prop="goodsSupplier.name" width="230"/>
      <el-table-column  label="人员姓名" align="center" prop="personName" />
      <el-table-column  align="center" label="付款类别" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_apply_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column sortable label="发票编号" align="center" prop="invoiceCode"/>
      <el-table-column  label="申请付款金额" align="center" prop="totalMoney"/>
      <el-table-column label="已付金额" align="center" prop="paidMoney"/>
      <el-table-column label="剩余金额" align="center" prop="remainMoney"/>
      <el-table-column align="center" label="审核状态" prop="assessStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apply_assess_status" :value="scope.row.assessStatus"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="付款状态" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apply_pay_status" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isTop"
            active-value="0"
            inactive-value="1"
            @change="handleIsTopChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-money" v-if="isEmpty(scope.row.invoicePhoto) && scope.row.type!=='4'"
                   @click="uploadInvoice(scope.row)" v-hasPermi="['develop:LvBuy:edit']">上传发票
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-finished"
                     v-if="scope.row.assessStatus === '0' || scope.row.assessStatus === '3'"
                     @click="handleAudit(scope.row)" v-hasPermi="['develop:PayApply:edit']">审计
          </el-button>

          <el-popconfirm :title="`确认同意撤销该付款单吗？`" @confirm="handleCancelApply(scope.row)"
                         v-if="scope.row.assessStatus === '1'"
                         style="margin: 0 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-remove-outline"> 撤销申请
            </el-button>
          </el-popconfirm>


          <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.assessStatus === '4'"
                     @click="payRecordList(scope.row)" v-hasPermi="['develop:LvBuy:edit']">打款记录
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.type ==='4'"
                     @click="handleDetailForShipping(scope.row)" v-hasPermi="['develop:PayApply:edit']">详情
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.type !=='4'"
                     @click="handleDetail(scope.row)" v-hasPermi="['develop:PayApply:edit']">详情
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-printer"
                     @click="handlePrintIron(scope.row)" v-hasPermi="['develop:PayApply:edit']">打印
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <lv-buy-list-module ref="buyListModule"></lv-buy-list-module>
    <lv-buy-list-deposit ref="buyListModuleDeposit"></lv-buy-list-deposit>
    <pay-record-form ref="payRecordForm" @ok="getList"></pay-record-form>
    <pay-record-shipping-form ref="payRecordShippingForm" @ok="getList"></pay-record-shipping-form>
    <pay-apply-detail ref="payApplyDetail"></pay-apply-detail>
    <pay-apply-shipping-detail ref="payApplyShippingDetail"></pay-apply-shipping-detail>
    <pay-record-list-module ref="payRecordList"></pay-record-list-module>
    <invoice-upload-form ref="invoiceUploadForm" @ok="getList"></invoice-upload-form>
    <pay-apply-detail-no-list-print ref="payApplyDetailPrint"></pay-apply-detail-no-list-print>

  </div>
</template>

<script>
import {accAdd, deleteAction, downloadFile, getAction, isEmpty, updateAction} from '@/api/manage'
import LvBuyListModule from "@/views/develop/lvBuy/module/LvBuyListModule.vue";
import LvBuyListHardware from "@/views/develop/lvBuy/module/LvBuyListDeposit.vue";
import PayRecordForm from "@/views/develop/payRecord/module/PayRecordForm.vue";
import PayApplyDetail from "@/views/develop/payApply/module/PayApplyDetail.vue";
import PayRecordListModule from "@/views/develop/payRecord/module/PayRecordListModule.vue";
import LvBuyListDeposit from "@/views/develop/lvBuy/module/LvBuyListDeposit.vue";
import InvoiceUploadForm from '@/views/develop/payApply/module/InvoiceUploadForm.vue';
import PayApplyShippingDetail from "@/views/develop/payApply/module/PayApplyShippingDetail.vue";
import PayRecordShippingForm from "@/views/develop/payRecord/module/PayRecordShippingForm.vue";
import PayApplyDetailNoListPrint from "@/views/develop/payApply/module/PayApplyDetailNoListPrint.vue";

export default {
  name: "PayApplyList",
  dicts: ["pay_apply_type", "apply_pay_status", "apply_assess_status","yes_no"],
  components: {
    PayApplyDetailNoListPrint,
    PayRecordShippingForm,
    PayApplyShippingDetail,
    LvBuyListDeposit,
    PayRecordListModule,
    PayApplyDetail,
    PayRecordForm,
    LvBuyListModule,
    LvBuyListHardware,
    InvoiceUploadForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款申请单表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        isInvoice: null,
        buyId: null,
        invoiceCode: null,
        assessStatus: null,
        createBy:this.$store.getters.name,
        params:{},
        orderByColumn: "isTop asc,applyTime",
        isAsc: "desc"
      },
      url: {
        list: '/payApply/payApply/list',
        remove: '/payApply/payApply/',
        cancel: '/payApply/payApply/cancel/',
        edit: '/payApply/payApply/edit',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    let that = this;
    that.queryParams.assessStatus = that.$route.query.assessStatus;
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    isEmpty,
    uploadInvoice(row) {
      this.$refs.invoiceUploadForm.handleUpdate(row);
    },
    /** 排序触发事件 */
		handleSortChange(column, prop, order) {
		  this.queryParams.orderByColumn = column.prop;
		  this.queryParams.isAsc = column.order;
		  this.handleQuery();
		},    /** 查询付款申请单列表 */
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAddMaterial() {
      this.$refs.buyListModule.show();
    },


    /** 新增按钮操作 */
    handleAddArrears() {
      this.$refs.buyListModuleDeposit.show("Y","3");
    },

    handleAddDeposit() {
      this.$refs.buyListModuleDeposit.show("Y","0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    payRecordForm(row) {
      this.$refs.payRecordForm.handleAddByApply(row);
    },



    handleDetail(row) {
      this.$refs.payApplyDetail.showDetail(row.id, row.buyId);
    },

    /** 运费详情 */
    handleDetailForShipping(row){
      this.$refs.payApplyShippingDetail.showDetail(row.id, row.buyId);
    },

    payRecordList(row) {
      let applyId = row.id;
      this.$refs.payRecordList.showPayRecordList(applyId);
    },

    handleCancelApply(row) {
      getAction(this.url.cancel+row.id, {}).then(response => {
        this.getList();
      }).catch(() => {
      });
    },

    handleAudit(row) {
      this.$refs.payAuditForm.handleUpdate(row);
    },
    handleAssess(row) {
      this.$refs.payAssessForm.handleUpdate(row);
    },

    handleBatchBossAssess(){
      const ids =  this.ids;
      this.$refs.payAssessFormBatch.handleBatchAssess(ids);
    },

    handlePrintIron(row) {
      this.$refs.payApplyDetailPrint.showDetail(row.id, row.buyId);
    },

    // 是否置顶修改
    handleIsTopChange(row) {
      let that = this;
      let text = row.isTop === "0" ? "置顶" : "取消置顶";
      this.$modal.confirm('确认要"' + text + '""' + row.nos + '"付款申请单吗？').then(function () {
        let params = {"id": row.id,"isTop":row.isTop};
        updateAction(that.url.edit, params).then(response => {
          that.getList();
        }).catch(() => {
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.isTop = row.isTop === "0" ? "1" : "0";
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      that.loading = false;
      that.$confirm('是否确认导出付款明细?', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        downloadFile('/payApply/payApply/export', that.queryParams);
      });
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "totalMoney" || column.property === "paidMoney" || column.property === "remainMoney") {
          sums[index] = values.reduce((prev, curr) => {

            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },







  }
};
</script>
